package com.zbkj.admin.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.mybatisflex.core.query.QueryMethods;
import com.mybatisflex.spring.service.impl.ServiceImpl;
import com.zbkj.admin.mapper1.EbUserVoucherRecordMapper;
import com.zbkj.admin.model.user.User;
import com.zbkj.admin.pojo.EbUserVoucherRecordEntity;
import com.zbkj.admin.response.UserInfoResponse;
import com.zbkj.admin.service.EbUserVoucherRecordService;
import com.zbkj.admin.service.UserService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import net.dreamlu.mica.core.result.R;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.Arrays;
import java.util.Objects;

@Slf4j
@Service
@RequiredArgsConstructor
public class EbUserVoucherRecordServiceImpl extends ServiceImpl<EbUserVoucherRecordMapper, EbUserVoucherRecordEntity> implements EbUserVoucherRecordService {

    private final UserService userService;

    /**
     * 获取用户额度
     *
     * @return 用户总额度
     */
    @Override
    public R<BigDecimal> limit() {
        User userInfo = userService.getInfo();
        if (Objects.isNull(userInfo)) {
            return R.fail("请登录后操作");
        }
        log.info("用户id:{}", userInfo.getId());
//        BigDecimal object = getObjAs(from().select(EbUserVoucherRecordEntity::getBalance)
//                .where(EbUserVoucherRecordEntity::getUid).eq(userInfo.getId())
//                        .orderBy(EbUserVoucherRecordEntity::getCreateTime).desc().limit(1)
//                , BigDecimal.class);
        return R.success(userInfo.getVoucher());
    }

    /**
     * 数据分页
     *
     * @param page      分页信息
     * @param state     分红状态
     * @param startDate 开始时间
     * @param endDate   结束时间
     * @return 分页数据
     */
    @Override
    public R<PageInfo<EbUserVoucherRecordEntity>> page(Page<EbUserVoucherRecordEntity> page,
                                                       Integer state, LocalDateTime startDate, LocalDateTime endDate) {
        User userInfo = userService.getInfo();
        PageInfo<EbUserVoucherRecordEntity> pageInfo = PageHelper.startPage(page.getPageNum(), page.getPageSize()).doSelectPageInfo(() ->
                list(from().where(EbUserVoucherRecordEntity::getCreateTime).ge(startDate)
                        .le(EbUserVoucherRecordEntity::getCreateTime, endDate)
                        .eq(EbUserVoucherRecordEntity::getStatus, state)
                        .eq(EbUserVoucherRecordEntity::getUid, userInfo.getId())
                        .orderBy(EbUserVoucherRecordEntity::getCreateTime).desc()));

        return R.success(pageInfo);
    }
}
